package com.bong.panpan.bongcharttools.activity;

import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.ArrayMap;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.bong.panpan.bongcharttools.R;
import com.bong.panpan.bongcharttools.adapter.CollectMACListAdapter;
import com.bong.panpan.bongcharttools.adapter.TempCollectListAdapter;
import com.bong.panpan.bongcharttools.ble.BleDeviceState;
import com.bong.panpan.bongcharttools.ble.BleLink;
import com.bong.panpan.bongcharttools.custom.BleStateRunnable2;
import com.bong.panpan.bongcharttools.custom.Constant;
import com.bong.panpan.bongcharttools.custom.MyUtil;
import com.bong.panpan.bongcharttools.custom.ObjectSaveUtil;
import com.bong.panpan.bongcharttools.custom.SpUtil;
import com.bong.panpan.bongcharttools.util.csvutil.FileUtils;
import com.bong.panpan.bongcharttools.util.csvutil.RecordEntity;
import com.bong.panpan.bongcharttools.util.csvutil.UsbHelper;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class TempCollectActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener, DrawerLayout.DrawerListener, BleLink.BleListener {

    private ListView macList;
    private CollectMACListAdapter macListAdapter;
    private Button scanButton;
    private Handler handler = new Handler();
    private ListView deviceList;
    private Button allBegin, allImport;
    private TempCollectListAdapter tempAdapter;
    private View textDevice;
    private boolean isDeviceChanged = false;
    private ArrayList<BleLink> bleLinks = new ArrayList<>();
    private ArrayList<Long> receiveTime = new ArrayList<>();
    private UsbHelper usbHelper;
    private File[] filesToSave = null;
    private ArrayMap<String, Boolean> scanMap = new ArrayMap<>();
    private TextView collectInterval;
    private int collectIntervalNum = 60;
    private AlertDialog alertDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_temp_collect);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        setTitle("体温采集系统");
//        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
//        fab.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
//                        .setAction("Action", null).show();
//            }
//        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();
        drawer.addDrawerListener(this);

        macListAdapter = new CollectMACListAdapter(this);
        macList = (ListView) findViewById(R.id.list_mac);
        macList.setAdapter(macListAdapter);
        scanButton = (Button) findViewById(R.id.button_scan);
        tempAdapter = new TempCollectListAdapter(this);
        deviceList = (ListView) findViewById(R.id.list_view);
        deviceList.setAdapter(tempAdapter);
        allBegin = (Button) findViewById(R.id.button_all_device);
        allImport = (Button) findViewById(R.id.button_data);
        textDevice = findViewById(R.id.text_device);
        collectInterval = (TextView) findViewById(R.id.text_interval);
        collectIntervalNum = SpUtil.getInstance().getInt("TempCollectActivity:collectInterval", 60);
        collectInterval.setText("采样间隔：" + collectIntervalNum / 60 + "min " + collectIntervalNum % 60 + "sec");
        initBle();
        loadConfigDevices();
        usbInit();
        macListAdapter.setClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int id=v.getId();
                int type = id % 10;
                int position =id / 10;
                if (type == 0) {
                    macListAdapter.remove(position);
                    MyUtil.showToast(TempCollectActivity.this, "设备移除成功");
                    isDeviceChanged = true;
                } else {
                    CollectMACListAdapter.CollectMACItem collectMACItem = macListAdapter.getItem(position).clone();
                    collectMACItem.type = 0;
                    if (macListAdapter.add(collectMACItem)) {
                        macListAdapter.remove(position + 1);//删除扫描
                        MyUtil.showToast(TempCollectActivity.this, "设备添加成功");
                        isDeviceChanged = true;
                    } else {
                        macListAdapter.remove(position);//删除扫描
                        MyUtil.showToast(TempCollectActivity.this, "设备已添加");
                    }
                }
            }
        });
        findViewById(R.id.button_clear).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                macListAdapter.clear();
            }
        });
        scanButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (scanButton.getText().toString().contains("扫描添加")) {
                    beginScan();
                } else {
                    stopScan();
                }
            }
        });
        allBegin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (allBegin.getText().toString().startsWith("全部开始")) {
                    allBegin.setText("全部停止采集数据");
                    for (int i = 0; i < tempAdapter.getCount(); i++) {
                        TempCollectListAdapter.TempCollectItem item = tempAdapter.getItem(i);
                        item.isBegin = true;
                    }
                    MyUtil.showToast(TempCollectActivity.this, "已全部开始采集");
                } else {
                    allBegin.setText("全部开始采集数据");
                    for (int i = 0; i < tempAdapter.getCount(); i++) {
                        TempCollectListAdapter.TempCollectItem item = tempAdapter.getItem(i);
                        item.isBegin = false;
                    }
                    MyUtil.showToast(TempCollectActivity.this, "已全部停止采集");
                }
            }
        });
        allImport.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (FileUtils.isExistUsbDevice(TempCollectActivity.this)) {
                    File file = new File(Constant.tempRecordPath);
                    File files[];
                    if (file.exists() && file.isDirectory() && (files = file.listFiles()).length > 0) {
                        filesToSave = files;
                        MyUtil.showToast(TempCollectActivity.this, "正在操作...");
                    } else {
                        MyUtil.showToast(TempCollectActivity.this, "未找到任何记录文件");
                    }
                } else {
                    MyUtil.showToast(TempCollectActivity.this, "未检测到U盘");
                }
            }
        });
        tempAdapter.setClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int id = v.getId();
                int position = id / 10;
                TempCollectListAdapter.TempCollectItem item = tempAdapter.getItem(position);
                if (id % 10 == 0) {
                    item.isBegin = !item.isBegin;
                    tempAdapter.notifyDataSetChanged();
                } else {//save
                    if (FileUtils.isExistUsbDevice(TempCollectActivity.this)) {
                        File file = new File(Constant.tempRecordPath + "/" + item.mac.replaceAll(":", "-") + ".csv");
                        if (file.exists() && file.isFile()) {
                            filesToSave = new File[]{file};
                            MyUtil.showToast(TempCollectActivity.this, "正在操作...");
                        } else {
                            MyUtil.showToast(TempCollectActivity.this, "未找到任何记录文件");
                        }
                    } else {
                        MyUtil.showToast(TempCollectActivity.this, "未检测到U盘");
                    }
                }
            }
        });
        collectInterval.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (alertDialog == null)
                    alertDialog = new AlertDialog.Builder(TempCollectActivity.this).setTitle("设置采样间隔")
                            .setView(R.layout.dialog_interval_layout)
                            .setNegativeButton("取消", null)
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    EditText alertMin = (EditText) alertDialog.findViewById(R.id.edit_min);
                                    EditText alertSec = (EditText) alertDialog.findViewById(R.id.edit_sec);
                                    if (alertMin.getText().toString().equals("") && alertSec.getText().toString().equals("")) {
                                        MyUtil.showToast(TempCollectActivity.this, "输入为空");
                                    } else {
                                        int min = 0, sec = 0;
                                        if (!alertMin.getText().toString().equals(""))
                                            min = Integer.valueOf(alertMin.getText().toString());
                                        if (!alertSec.getText().toString().equals(""))
                                            sec = Integer.valueOf(alertSec.getText().toString());
                                        collectIntervalNum = min * 60 + sec;
                                        SpUtil.getInstance().setInt("TempCollectActivity:collectInterval", collectIntervalNum);
                                        collectInterval.setText("采样间隔：" + collectIntervalNum / 60 + "min " + collectIntervalNum % 60 + "sec");
                                        MyUtil.showToast(TempCollectActivity.this, "设置成功");
                                    }
                                }
                            })
                            .create();
                alertDialog.show();
                EditText alertMin = (EditText) alertDialog.findViewById(R.id.edit_min);
                EditText alertSec = (EditText) alertDialog.findViewById(R.id.edit_sec);
                alertMin.setText("" + collectIntervalNum / 60);
                alertSec.setText("" + collectIntervalNum % 60);
            }
        });
        startReadThread();
    }

    private void saveAllToUSB() {
        if (filesToSave == null)
            return;
        File files[] = filesToSave;
        for (File file2 : files) {
            try {
                usbHelper.saveFileToUsb(file2, "TempRecord");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        MyUtil.showToast(TempCollectActivity.this, "成功导出");
                    }
                });
            } catch (final Exception e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        MyUtil.showAlertDialog(TempCollectActivity.this, "出错", "保存到U盘失败：" + e.getMessage(), null);
                    }
                });
                break;
            }
        }
        filesToSave = null;
    }

    private void usbInit() {
        usbHelper = new UsbHelper(this);
        usbHelper.setOnUsbOperateListener(new UsbHelper.OnUsbOperateListener() {
            @Override
            public void onInsert() {
                tempAdapter.setImportEnable(true);
                allImport.setEnabled(true);
            }

            @Override
            public void onPullOut() {
                tempAdapter.setImportEnable(false);
                allImport.setEnabled(false);
            }

            @Override
            public void unrecognized() {
                tempAdapter.setImportEnable(false);
                allImport.setEnabled(false);
                MyUtil.showAlertDialog(TempCollectActivity.this, "错误", "U盘无法识别，请确保是U盘设备且文件系统为FAT32", null);
            }

            @Override
            public void onPermissionCancel() {
                tempAdapter.setImportEnable(false);
                allImport.setEnabled(false);
            }

            @Override
            public void onPermissionGranted() {
                tempAdapter.setImportEnable(true);
                allImport.setEnabled(true);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        usbHelper.onResume();
        if (FileUtils.isExistUsbDevice(this)) {
            tempAdapter.setImportEnable(true);
            allImport.setEnabled(true);
        } else {
            tempAdapter.setImportEnable(false);
            allImport.setEnabled(false);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        usbHelper.onPause();
    }

    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothManager bluetoothManager;
    CollectMACListAdapter.CollectMACItem collectMACItem = new CollectMACListAdapter.CollectMACItem();
    private ScanCallback scanCallback = new ScanCallback() {
        /**
         * Callback when a BLE advertisement has been found.
         *
         * @param callbackType Determines how this callback was triggered. Could be one of
         *                     {ScanSettings#CALLBACK_TYPE_ALL_MATCHES},
         *                     {ScanSettings#CALLBACK_TYPE_FIRST_MATCH} or
         *                     {ScanSettings#CALLBACK_TYPE_MATCH_LOST}
         * @param result       A Bluetooth LE scan result.
         */
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            BluetoothDevice device = result.getDevice();
            String mac = device.getAddress();
            String name = device.getName();
            collectMACItem.type = 1;
            collectMACItem.rssi = result.getRssi();
            collectMACItem.mac = mac;
            macListAdapter.add(collectMACItem);
        }

        @Override
        public void onBatchScanResults(List<ScanResult> results) {
            for (ScanResult result : results) {
                BluetoothDevice device = result.getDevice();
                String mac = device.getAddress();
                String name = device.getName();
                collectMACItem.type = 1;
                collectMACItem.rssi = result.getRssi();
                collectMACItem.mac = mac;
                macListAdapter.add(collectMACItem);
            }
        }

        /**
         * Callback when scan could not be started.
         *
         * @param errorCode Error code (one of SCAN_FAILED_*) for scan failure.
         */
        @Override
        public void onScanFailed(int errorCode) {
            super.onScanFailed(errorCode);
            if (errorCode != SCAN_FAILED_ALREADY_STARTED) {
                scanButton.setText("扫描添加设备");
                MyUtil.showToast(TempCollectActivity.this, "扫描失败：" + errorCode);
            }
        }
    };

    private void initBle() {
        bluetoothManager =
                (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();
        // Checks if Bluetooth is supported on the device.
        if (mBluetoothAdapter == null) {
            finish();
            return;
        }
        mBluetoothAdapter.enable();
    }

    Runnable stopScan = new Runnable() {
        @Override
        public void run() {
            stopScan();
        }
    };

    public void beginScan() {
        if (scanButton.getText().toString().contains("扫描添加")) {
            isScanning = true;
            scanButton.setText("正在扫描");
            mBluetoothAdapter.getBluetoothLeScanner().stopScan(scanCallback);
            List<ScanFilter> scanFilters = new ArrayList<>();
            scanFilters.add(new ScanFilter.Builder().setDeviceName("BongTemp").build());
            ScanSettings scanSettings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build();
            mBluetoothAdapter.getBluetoothLeScanner().startScan(scanFilters, scanSettings, scanCallback);
            handler.postDelayed(stopScan, 20000);//20s后停止扫描
        }
    }

    public void stopScan() {
        if (scanButton.getText().toString().contains("扫描添加")) {
        } else {
            isScanning = false;
            scanButton.setText("扫描添加设备");
            handler.removeCallbacks(stopScan);
            mBluetoothAdapter.getBluetoothLeScanner().stopScan(scanCallback);
        }
    }

    ScanCallback scanCallback2 = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            scanMap.put(result.getDevice().getAddress(), true);
        }

        @Override
        public void onBatchScanResults(List<ScanResult> results) {
            for (ScanResult result : results) {
                scanMap.put(result.getDevice().getAddress(), true);
            }
        }

        @Override
        public void onScanFailed(int errorCode) {
            if (errorCode != SCAN_FAILED_ALREADY_STARTED)
                isScanning = false;
            super.onScanFailed(errorCode);
        }
    };
    boolean isScanning = false;
    long scanTime = 0;

    public void beginScan2() {
        if (isScanning)
            return;
        Log.d("Scan", "beginScan2");
        stopScan2();
        isScanning = true;
        List<ScanFilter> scanFilters = new ArrayList<>();
        scanFilters.add(new ScanFilter.Builder().setDeviceName("BongTemp").build());
        ScanSettings scanSettings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build();
        mBluetoothAdapter.getBluetoothLeScanner().startScan(scanFilters, scanSettings, scanCallback2);
    }

    public void stopScan2() {
        if (!isScanning)
            return;
        Log.d("Scan", "stopScan2");
        isScanning = false;
        mBluetoothAdapter.getBluetoothLeScanner().stopScan(scanCallback2);
    }

    private void dealScan(boolean linkOk) {
        if (scanButton.getText().toString().contains("正在扫描"))
            return;
        if (linkOk) {
            stopScan2();
        } else {
            if (System.currentTimeMillis() - scanTime > 20000)//重新开启扫描
            {
                scanTime = System.currentTimeMillis();
                isScanning = false;
            }
            beginScan2();
        }
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.temp_collect, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            // Handle the camera action
        } else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void onDrawerSlide(View drawerView, float slideOffset) {

    }

    @Override
    public void onDrawerOpened(View drawerView) {

    }

    @Override
    public void onDrawerClosed(View drawerView) {
        if (isDeviceChanged) {
            isDeviceChanged = false;
            loadConfigDevices();
        }
    }

    @Override
    public void onDrawerStateChanged(int newState) {

    }

    private void loadConfigDevices() {
        ArrayList<CollectMACListAdapter.CollectMACItem> items = macListAdapter.getConfigItem();
        try {
            ObjectSaveUtil.saveCache(items, "CollectMACListAdapter.dat");
        } catch (Exception e) {
            e.printStackTrace();
        }
        tempAdapter.clear();
        if (items.size() == 0)
            textDevice.setVisibility(View.VISIBLE);
        else
            textDevice.setVisibility(View.GONE);
        for (int i = 0; i < items.size(); i++) {
            TempCollectListAdapter.TempCollectItem item2 = new TempCollectListAdapter.TempCollectItem();
            item2.mac = items.get(i).mac;
            tempAdapter.add(item2);
        }
        for (int i = 0; i < bleLinks.size(); i++) {
            bleLinks.get(i).removeBleListener();
            bleLinks.get(i).dislink();
        }
        bleLinks.clear();
        for (int i = 0; i < items.size(); i++) {
            BleLink bleLink = new BleLink(this);
            bleLink.addBleListener(this);
            bleLinks.add(bleLink);
        }
        receiveTime.clear();
        for (int i = 0; i < items.size(); i++) {
            receiveTime.add(0l);
        }
    }

    @Override
    public void OnDeviceStateChanged(BleLink bleLink, BleDeviceState state) {
        BleStateRunnable2 runnable = new BleStateRunnable2(bleLink, state) {
            @Override
            public void OnDeviceStateChanged(BleLink bleLink, BleDeviceState state) {
                String mac = bleLink.getAddress();
                final TempCollectListAdapter.TempCollectItem item = tempAdapter.getItem(mac);
                switch (state) {
                    case DEVICE_STATE_LINKING:
                        item.state = "连接中";
                        break;
                    case DEVICE_STATE_LINKED:
                        item.state = "已连接";
                        break;
                    case DEVICE_STATE_DISLINK:
                        item.state = "未连接";
                        break;
                    case DEVICE_STATE_LINKFAILED:
                        MyUtil.showToast(TempCollectActivity.this, "连接失败");
                        break;
                    case DEVICE_STATE_LINKLOST:
                        MyUtil.showToast(TempCollectActivity.this, "连接丢失");
                        break;
                }
                tempAdapter.notifyDataSetChanged();
            }
        };
        runOnUiThread(runnable);
    }

    @Override
    public void OnDataReceived(BleLink bleLink, byte[] data) {
        receivedSem.release();
    }

    private Thread dataReadThread;
    private Semaphore receivedSem = new Semaphore(0);

    private void startReadThread() {
        if (dataReadThread != null && dataReadThread.isAlive())
            return;
        dataReadThread = new Thread(new Runnable() {
            @Override
            public void run() {
                int i;
                BleLink bleLink;
                final byte[] command = new byte[]{(byte) 0x26, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x21};
                ArrayList<Integer> sendList = new ArrayList<>();
                Log.d("DataReadThread", "Start");
                Runnable adapterRunnable = new Runnable() {
                    @Override
                    public void run() {
                        tempAdapter.notifyDataSetChanged();
                    }
                };
                TempCollectListAdapter.TempCollectItem collectItem;
                List<RecordEntity> entities = new ArrayList<>();
                RecordEntity entity = new RecordEntity();
                entities.add(entity);
                boolean isAllLinked = false;
                long exerciseAmount = 0;
                while (true) {
                    try {
                        //Log.d("DataReadThread","Run");
                        //连接
                        for (i = 0; i < bleLinks.size(); i++) {
                            bleLink = bleLinks.get(i);
                            collectItem = tempAdapter.getItem(i);
                            if (bleLink != null) {
                                if (collectItem.isBegin && bleLink.getDeviceState() == BleDeviceState.DEVICE_STATE_DISLINK) {
                                    bleLink.dislink();
                                    if (bleLink.link(mBluetoothAdapter.getRemoteDevice(collectItem.mac))) {
                                        Log.d("DataReadThread", "Linking");
                                    } else {
                                        Log.d("DataReadThread", "Link Failed");
                                    }
                                } else if (!collectItem.isBegin && bleLink.getDeviceState() != BleDeviceState.DEVICE_STATE_DISLINK) {
                                    bleLink.dislink();
                                }
                                if (bleLink.getDeviceState() == BleDeviceState.DEVICE_STATE_LINKED) {
                                    tempAdapter.getItem(i).rssi = bleLink.getRssi();
                                    runOnUiThread(adapterRunnable);
                                }
                            }
                        }
                        //发送数据
                        sendList.clear();
                        isAllLinked = true;
                        for (i = 0; i < bleLinks.size(); i++) {
                            bleLink = bleLinks.get(i);
                            if (bleLink == null || bleLink.getDeviceState() != BleDeviceState.DEVICE_STATE_LINKED) {
                                if (tempAdapter.getItem(i).isBegin)
                                    isAllLinked = false;
                            }
                            if (System.currentTimeMillis() - receiveTime.get(i) >= collectIntervalNum * 1000L)
                                if (bleLink != null && bleLink.sendData(command))//发送成功
                                {
                                    sendList.add(i);
                                }
                        }
                        //接收数据
                        if (sendList.size() > 0) {
                            if (receivedSem.tryAcquire(sendList.size(), 5, TimeUnit.SECONDS)) {
                                Log.d("DataReadThread", "All Received");
                            }
                            for (i = 0; i < sendList.size(); i++) {
                                int index = sendList.get(i);
                                receiveTime.set(index, System.currentTimeMillis());
                                int[] data = MyUtil.byte2IntArray(bleLinks.get(index).readData());
                                final float tempValue = ((data[0] << 8) | data[1]) / 1000.0f;
                                TempCollectListAdapter.TempCollectItem item = tempAdapter.getItem(index);
                                if (data.length >= 7) {
                                    exerciseAmount = (((long) data[2] << 24) | (data[3] << 16) | (data[4] << 8) | data[5]);
                                    item.info = String.format("时间:%s 温度:%.3f℃\n运动量统计：%s 运动量：%d",
                                            new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date()),
                                            tempValue,
                                            data[6] == 1 ? "打开" : "关闭",
                                            exerciseAmount

                                    );
                                } else {
                                    item.info = String.format("时间:%s 温度:%.3f℃",
                                            new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date()),
                                            tempValue
                                    );
                                }
                                //更新UI
                                try {
                                    RecordEntity entry = entities.get(0);
                                    entry.setTime(new Date());
                                    entry.setTemp(tempValue);
                                    entity.setAct((float) exerciseAmount);
                                    FileUtils.addRecord(Constant.tempRecordPath + "/" + item.mac.replaceAll(":", "-") + ".csv", entities);
                                    item.num++;
                                } catch (final IOException e) {
                                    e.printStackTrace();
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            MyUtil.showToast(TempCollectActivity.this, "数据保存失败:" + e.getMessage());
                                        }
                                    });
                                }
                            }
                            runOnUiThread(adapterRunnable);
                        }
                        Thread.sleep(200);
                        saveAllToUSB();
                        dealScan(bleLinks.size() > 0 && isAllLinked);
                    } catch (InterruptedException e) {
                        break;
                    } catch (Exception e) {

                    }
                }
                for (i = 0; i < bleLinks.size(); i++) {
                    bleLink = bleLinks.get(i);
                    if (bleLink != null)
                        bleLink.dislink();
                }
                bleLinks.clear();
                Log.d("DataReadThread", "Stopped");
            }
        });
        dataReadThread.setName("数据读取线程");
        dataReadThread.start();
    }

    private void stopReadThread() {
        if (dataReadThread == null || !dataReadThread.isAlive())
            return;
        dataReadThread.interrupt();
    }

    @Override
    protected void onDestroy() {
        stopReadThread();
        usbHelper.onDestory();
        super.onDestroy();
    }
}
